﻿using AntdUI;
using DataTurnClient.Enum;
using DataTurnClient.Interface;
using DataTurnClient.Model;
using DataTurnClient.ViewModel;
using HttpLib;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using Splat;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DataTurnClient.Server
{
    public class Tool : ITool
    {
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public T JsonToList<T>(string filePath)
        {
            string jsonStr = File.ReadAllText(filePath);
            //反序列化
            var list = JsonConvert.DeserializeObject<T>(jsonStr);
            return list;
        }

        public string MsgShow(Job job)
        {
            string status = job.JobStatus == 1 ? "开" : "关";
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"《任务名》：{job.JobCode}-{job.JobName}");
            sb.AppendLine($"《任务描述》");
            sb.AppendLine($"{job.JobDetail}");
            sb.AppendLine($"《任务状态》：{ status}");
            sb.AppendLine($"《请求模式》：{ job.JobMode}");
            sb.AppendLine($"《任务路由》：{ job.JobRoute}");
            sb.AppendLine($"《任务运行时间》");
            sb.AppendLine($"{job.JobRunTime}");
            sb.AppendLine($"{job.JobWeek}");
            return sb.ToString();
        }

        public string LogShow(Log log)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"《发生时间》：{log.HappenTime}");
            sb.AppendLine($"《发生描述》");
            sb.AppendLine($"{log.HappenDtal}");
            return sb.ToString();
        }
        /// <summary>
        /// xml读取
        /// </summary>
        public Result<string> XmlRead(string name)
        {
            Result<string> result = new Result<string>();
            result.Code = 500;
            result.Message = "未找到改key";
            result.Success = false;
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load("Version.xml");
                System.Xml.XmlElement root = doc.DocumentElement;
                System.Xml.XmlNodeList personNodes = root.GetElementsByTagName("Person"); //获取Person子节点集合 
                foreach (System.Xml.XmlNode node in personNodes)
                {
                    string id = ((System.Xml.XmlElement)node).GetAttribute("id");   //获取Name属性值 
                    string Value = ((System.Xml.XmlElement)node).GetElementsByTagName("Value")[0].InnerText;
                    if (id == name)
                    {
                        result.Code = 200;
                        result.Message = "请求成功";
                        result.Success = true;
                        result.Data = Value.ToString();
                        return result;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = $"{name}请求XmlRead时遇到错误：{ex.Message}";
                result.Success = false;
                return result;
            }
        }
        /// <summary>
        /// xml写入
        /// </summary>
        public Result<string> XmlWrith(string key, string keyName)
        {
            string fileName = "Version.xml";
            Result<string>  result = new Result<string>();
            result.Code = 500;
            result.Message = "未找到改key";
            result.Success = false;
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(fileName);    //加载Xml文件 
                System.Xml.XmlElement root = doc.DocumentElement;   //获取根节点 
                System.Xml.XmlNodeList personNodes = root.GetElementsByTagName("Person"); //获取Person子节点集合
                foreach (System.Xml.XmlNode node in personNodes)
                {
                    System.Xml.XmlElement ele = (System.Xml.XmlElement)node;
                    if (ele.GetAttribute("id") == key)
                    {
                        System.Xml.XmlElement nameEle = (System.Xml.XmlElement)ele.GetElementsByTagName("Value")[0];
                        nameEle.InnerText = keyName;
                        result.Code = 200;
                        result.Message = "请求成功";
                        result.Success = true;
                        return result;
                    }
                }
                doc.Save(fileName);
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = $"{key}请求XmlWrith时遇到错误：{ex.Message}";
                result.Success = false;
                return result;
            }
        }

        /// <summary>
        /// 发送接口请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public Result<T> PostRequest<T>(string url,T data, DType.RequestType type)
        {
            Post<T> p = new Post<T>
            {
                Post_url = url,
                Post_data = data,
                Post_mode = type,
            };
            return p.PostSend();
        }

        /// <summary>
        /// 核心方法，接口请求
        /// </summary>
        /// <param name="jobList"></param>
        /// <param name="setList"></param>
        /// <param name="sender"></param>
        /// <returns></returns>
        public Result<string> Execute(List<Job> jobList, List<RouteLine> setList, object sender)
        {
            Result<string> result = new Result<string>()
            {
                Code = 200,
                Success = true,
                Message = "请求成功"
            };
            List<Val> headerss = new List<Val> {
                new Val("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"),
                new Val("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36 Edg/86.0.622.63"),
            };
            var jobs = jobList.Where(x => x.JobCode == sender.ToString()).FirstOrDefault();
            var service = Locator.Current.GetService<ITool>();
            string url = TaskRequest.Url(jobs);
            switch (jobs.JobMode)
            {
                case "Get":
                    string getRequest = Http.Get(url).header(headerss)
                    .redirect()
                    .request();
                    result.Data = getRequest;
                    break;

                case "Post":
                    string postRequest = Http.Post(url).header(headerss)
                    .redirect()
                    .request();
                    result.Data = postRequest;
                    break;
            }
            jobs.JobRunStatus = Job.JobRunType.Over;
            service.WriterText("auto ", DateTime.Now.ToString("HH-mm-ss") + $"      {jobs.JobCode}" + JsonConvert.SerializeObject(result));
            HttpLib.Config.fail += (HttpCore core, ResultResponse err) =>
            {
                result.Code = 500;
                result.Message = $"请求{sender}时遇到错误：{err.Exception.Message}";
                result.Success = false;
                jobs.JobRunStatus = Job.JobRunType.Over;
                service.WriterText("auto ", DateTime.Now.ToString("HH-mm-ss") + $"      {jobs.JobCode}" + err.Exception.Message);
            };
            return result;
        }

        /// <summary>
        /// 核心方法，检查任务运行星期内
        /// </summary>
        /// <param name="jobWeek"></param>
        /// <returns></returns>
        public bool IsWeek(string jobWeek)
        {
            var server = Locator.Current.GetService<TimeService>();
            return server.IsWeek(jobWeek);
        }

        /// <summary>
        /// 核心方法，检查是否在任务运行秒时分内
        /// </summary>
        /// <param name="jobTimeList"></param>
        /// <param name="newTime"></param>
        /// <returns></returns>
        public bool IsTime(List<JobTime> jobTimeList, List<string> newTime)
        {
            var server = Locator.Current.GetService<TimeService>();
            return server.IsTime(jobTimeList,newTime);
        }

        /// <summary>
        /// txt写入
        /// </summary>
        /// <param name="txtName"></param>
        /// <param name="txt"></param>
        public void WriterText(string txtName, string txt)
        {
            var server = Locator.Current.GetService<LogService>();
            server.WriterText(txtName,txt);
        }

        public bool CheckControlData(System.Windows.Forms.Control controls)
        {
            bool pass = true;
            var message = Locator.Current.GetService<IAntdMessage>();
            foreach (var control in controls.Controls)
            {
                if (control is AntdUI.Input)
                {
                    if (string.IsNullOrEmpty((control as AntdUI.Input).Text) && ((control as AntdUI.Input).Tag == null || (control as AntdUI.Input).Tag.ToString() != "True"))
                    {
                        var config = message.TooltipConfig((control as AntdUI.Input), "不可为空");
                        AntdUI.Tooltip.open(config);
                        pass = false;
                    }
                }
                if (control is AntdUI.Select)
                {
                    if ((control as AntdUI.Select).SelectedIndex < 0 && ((control as AntdUI.Select).Tag == null || (control as AntdUI.Select).Tag.ToString() != "True"))
                    {
                        var config = message.TooltipConfig((control as AntdUI.Select), "不可为空");
                        AntdUI.Tooltip.open(config);
                        pass = false;
                    }
                }
                if (control is AntdUI.FlowPanel)
                {
                    if ((control as AntdUI.FlowPanel).Controls.Count == 0)
                    {
                        var config = message.TooltipConfig((control as AntdUI.FlowPanel), "不可为空");
                        AntdUI.Tooltip.open(config);
                        pass = false;
                    }
                }
            }
            return pass;
        }

    }
}
